package com.xli.metadata.frameconfigcategory.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xli.dto.component.TreeNode;
import com.xli.dto.component.model.TableModel;
import com.xli.dto.component.model.TreeModel;
import com.xli.dto.component.util.TreeUtil;
import com.xli.dto.controller.BaseController;
import com.xli.dto.params.IdsDTO;
import com.xli.dto.result.ResultVO;
import com.xli.dto.result.status.Status;
import com.xli.dto.validation.group.IGroup;
import com.xli.metadata.frameconfigcategory.entity.FrameConfigCategory;
import com.xli.metadata.frameconfigcategory.entity.dto.ConfigCategoryAddDTO;
import com.xli.metadata.frameconfigcategory.entity.dto.ConfigCategorySearchDTO;
import com.xli.metadata.frameconfigcategory.entity.dto.ConfigCategoryUpdateDTO;
import com.xli.metadata.frameconfigcategory.entity.mapper.IFrameConfigCategoryMapper;
import com.xli.metadata.frameconfigcategory.entity.vo.ConfigCategoryVO;
import com.xli.metadata.frameconfigcategory.service.IFrameConfigCategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Tag(name = "参数分类")
@RestController
@RequestMapping("/frameConfigCategory")
public class FrameConfigCategoryController extends BaseController {

    @Autowired
    private IFrameConfigCategoryService iFrameConfigCategoryService;

    @Operation(summary = "保存分类", description = "保存分类")
    @PostMapping(value = "/add")
    public ResultVO<String> add(@RequestBody @Validated(IGroup.add.class) ConfigCategoryAddDTO dto) {
        FrameConfigCategory frameConfigCategory = iFrameConfigCategoryService.findCategoryByName(dto.getCategoryName());
        if (frameConfigCategory == null) {
            frameConfigCategory = IFrameConfigCategoryMapper.INSTANCE.toEntity(dto);
            frameConfigCategory.setId(IdUtil.getSnowflakeNextId());
            boolean result = iFrameConfigCategoryService.insert(frameConfigCategory);
            if (result) {
                return new ResultVO<>(Status.SUCCESS, "保存成功");
            }
            return new ResultVO<>(Status.FAILED, "保存失败");
        }
        return new ResultVO<>(Status.FAILED, "保存失败，分类已存在");
    }

    @Operation(summary = "删除分类", description = "删除分类")
    @PostMapping(value = "/delete")
    public ResultVO<String> delete(@RequestBody @Validated(IGroup.delete.class) IdsDTO dto) {
        int i = 0;
        for (String id : dto.getIds()) {
            if (iFrameConfigCategoryService.delete(Long.valueOf(id))) {
                i++;
            }
        }
        return new ResultVO<>(Status.SUCCESS, i + "条数据删除成功");
    }

    @Operation(summary = "更新分类", description = "更新分类")
    @PostMapping(value = "/update")
    public ResultVO<String> update(@RequestBody @Validated(IGroup.update.class) ConfigCategoryUpdateDTO dto) {
        FrameConfigCategory frameConfigCategory = iFrameConfigCategoryService.findCategoryByName(dto.getCategoryName());
        if (frameConfigCategory == null || frameConfigCategory.getId().toString().equals(dto.getId())) {
            if (iFrameConfigCategoryService.update(IFrameConfigCategoryMapper.INSTANCE.toEntity(dto))) {
                return new ResultVO<>(Status.SUCCESS, "更新成功");
            }
            return new ResultVO<>(Status.FAILED, "更新失败");
        }
        return new ResultVO<>(Status.FAILED, "更新失败，分类已存在");
    }

    @Operation(summary = "查询分类详情", description = "查询分类详情")
    @PostMapping(value = "/detail/{id}")
    public ResultVO<ConfigCategoryVO> detail(@PathVariable("id") @NotBlank(message = "id不能为空") String id) {
        FrameConfigCategory frameConfigCategory = iFrameConfigCategoryService.find(Long.valueOf(id));
        if (frameConfigCategory != null) {
            ConfigCategoryVO configCategoryVO = IFrameConfigCategoryMapper.INSTANCE.toVO(frameConfigCategory);
            return new ResultVO<>(Status.SUCCESS, "查询成功", configCategoryVO);
        }
        return new ResultVO<>(Status.SUCCESS, "查询失败");
    }

    @Operation(summary = "查询分类列表", description = "查询分类列表")
    @PostMapping(value = "/search")
    public ResultVO<TableModel<ConfigCategoryVO, FrameConfigCategory, ConfigCategorySearchDTO>> search(@RequestBody @Validated(IGroup.search.class) ConfigCategorySearchDTO dto) {

        TableModel<ConfigCategoryVO, FrameConfigCategory, ConfigCategorySearchDTO> tableModel = new TableModel<>(dto) {
            @Override
            public List<ConfigCategoryVO> fetch(int current, int pageSize) {
                Page<FrameConfigCategory> page = iFrameConfigCategoryService.findList(getQueryWrapper(), current, pageSize);
                this.setTotal(page.getTotal());
                return page.convert(IFrameConfigCategoryMapper.INSTANCE::toVO).getRecords();
            }
        };
        return new ResultVO<>(Status.SUCCESS, "查询成功", tableModel);
    }

    @Operation(summary = "查询分类树", description = "查询分类树")
    @PostMapping(value = "/fetchTree")
    public ResultVO<TreeModel<ConfigCategoryVO>> fetchTree() {
        // TODO
        TreeModel<ConfigCategoryVO> treeModel = new TreeModel<>() {
            @Override
            public List<TreeNode<ConfigCategoryVO>> fetch() {
                List<TreeNode<ConfigCategoryVO>> treeNodeList = new ArrayList<>();
                List<FrameConfigCategory> frameConfigCategoryList = iFrameConfigCategoryService.findList(new QueryWrapper<>());
                for (FrameConfigCategory frameConfigCategory : frameConfigCategoryList) {
                    ConfigCategoryVO configCategoryVO = IFrameConfigCategoryMapper.INSTANCE.toVO(frameConfigCategory);
                    TreeNode<ConfigCategoryVO> node = new TreeNode<>();
                    node.setId(frameConfigCategory.getId());
                    node.setText(configCategoryVO.getCategoryName());
                    node.setPid(TreeUtil.defaultPid);
                    treeNodeList.add(node);
                }

                return treeNodeList;
            }
        };
        return new ResultVO<>(Status.SUCCESS, "查询成功", treeModel);
    }
}
